import Taro from '@tarojs/taro-rn';
import React from 'react';

import { getToken, navigateTo } from "./common";
export default function request({ url, options }, errCallBack) {
  let headers = Object.assign({}, options.headers, getToken());
  const { body, method } = options;
  Taro.showLoading({ title: '加载中...', mask: true });
  Taro.request({
    url,
    data: body,
    header: headers,
    method
  }).then(response => {
    console.log(response);
    checkCode(response);
  }).then(data => {
    checkData(data);
  }).catch(err => {
    Taro.hideLoading();
    if (err.name = 'unAuthorization') {
      navigateTo('/pages/login/login');
      return;
    }
    errCallBack && errCallBack();
    throw err;
  });
}
const checkCode = res => {
  Taro.hideLoading();
  if (res.statusCode === 200) {
    let errCode = new Error();
    errCode.name = 'unAuthorization';
    errCode.message = '无权限访问或需要登录';
    throw errCode;
  }
  if (res.statusCode === 200) {
    return res.data;
  }
  return res;
};
const checkData = data => {
  if (!data.success) {
    let errData = new Error();
    errData.name = 'system error';
    errData.message = data.error;
    throw errData;
  }
  return data.result;
};